<?php
namespace app\api\controller;
use addons\message\model\NewsMessage;
use app\admin\model\publicuse\HerTime;
use app\api\model\AllOrder;
use app\api\model\CommentUser;
use app\api\model\EscortType;
use app\api\model\Feedback;
use app\api\model\NannyOptions;
use app\api\model\Notice;
use app\api\model\NursingLang;
use app\api\model\NursingOrder;
use app\api\model\OptionType;
use app\api\model\PlatformFee;
use app\api\model\Users;
use app\BaseController;
use app\staff\model\OrderCheck;
use think\facade\Cache;
use think\Request;

class Userhand extends BaseController
{
    /**获取用户未读消息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_message_count(Request $request){
        $user = $request->user;
        $count = NewsMessage::getUserCount($user['id']);
        return api_success('获取成功',$count);
    }

    /**获取消息列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function get_message_list(Request $request){
        $limit = $request->param('limit',10);
        $user = $request->user;
        $data = NewsMessage::getUserMessageList($user['id'],$limit);
        return api_success('获取成功',$data);
    }

    /**获取公告列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function get_notice_list(Request $request){
        $user = $request->user;
//        $up_getmessage_time = Users::where('id',$user['id'])
//            ->value('up_getmessage_time');
        $limit = $request->param('limit',10);
        $data = Notice::where('status',1)
            ->where('type','in',[0,1])
            ->withoutField('sort,delete_time,type')
            ->paginate($limit)
            ->toArray();
        $page = $request->param('page');
        if($page==1){
            Users::where('id',$user['id'])->save(['up_getmessage_time'=>time()]);
        }
        return api_success('获取成功',$data['data']);
    }

    /**获取公告详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_notice_info(Request $request){
        $id = $request->param('id');
        $data = Notice::where('id',$id)
            ->withoutField('sort,delete_time,type')
            ->findOrEmpty()->toArray();
        return api_success('获取成功',$data);
    }

    /**获取消息详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_message_info(Request $request){
        $user = $request->user;
        $id = $request->param('id');
        $data = NewsMessage::where('id',$id)
            ->withoutField('sort,delete_time')
            ->find();
        if(empty($data)){
            return api_fail('消息不存在');
        }
        $data->read = 1;
        $data->save(['update_time'=>time()]);
        return api_success('获取成功',$data->toArray());
    }

    /**护理预约上门
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function home_assessment(Request $request){
        $user = $request->user;
        $data = $request->param();
        $array = [
            'nursing_id|选择的服务'=>'require',
            'cover_pepo_name|被护理人的姓名'=>'require',
            'cover_pepo_sex|被护理人的性别'=>'require',
            'province|所在区域'=>'require',
            'city|所在区域'=>'require',
            'area|所在区域'=>'require',
            'address|详细地址'=>'require',
//            'address|详细地址'=>'require',
            'phone|联系电话'=>'require|mobile',
            'assessment_time|上面评估时间'=>'require',
        ];
        $this->validate($data,$array);
        $nursing_lang = NursingLang::where('status',1)
            ->where('id',$data['nursing_id'])
            ->find();
        if(empty($nursing_lang)){
            return api_fail('服务不存在');
        }
        $newdata = [
            'name'=>$nursing_lang->name,
            'order_num'=>getOrder($user['id'],'ZS'),
            'nursing_lang_id'=>$nursing_lang->id,
            'cover_pepo_name'=>$data['cover_pepo_name'],
            'cover_pepo_sex'=>$data['cover_pepo_sex'],
            'phone'=>$data['phone'],
            'province'=>$data['province'],
            'city'=>$data['city'],
            'area'=>$data['area'],
            'address'=>$data['address'],
            'assessment_time'=>strtotime($data['assessment_time']),
            'uid'=>$user['id'],
            'is_assessment'=>1,
            'state'=>1,
            'status'=>1,
            'create_time'=>time(),
            'update_time'=>time(),
        ];
        $bool = NursingOrder::create($newdata);
        if(!$bool){
            return api_fail('预约失败');
        }
        $nursing_lang->inc('get_order_num_count',1)->update();
        return api_success('预约成功');
    }

    /**保姆预约上门
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function nanny_home_assessment(Request $request){
        $user = $request->user;
        $data = $request->param();
        $array = [
            'nursing_id|选择的服务'=>'require',
//            'cover_pepo_name|被护理人的姓名'=>'require',
//            'cover_pepo_sex|被护理人的性别'=>'require',
            'province|所在区域'=>'require',
            'city|所在区域'=>'require',
            'area|所在区域'=>'require',
            'address|详细地址'=>'require',
//            'address|详细地址'=>'require',
            'phone|联系电话'=>'require|mobile',
            'contact_name|联系人姓名'=>'require',
            'assessment_time|上面评估时间'=>'require',
        ];
        $this->validate($data,$array);
        $nursing_lang = NursingLang::where('status',1)
            ->where('id',$data['nursing_id'])
            ->find();
        if(empty($nursing_lang)){
            return api_fail('服务不存在');
        }
        $newdata = [
            'name'=>$nursing_lang->name,
            'order_num'=>getOrder($user['id'],'ZS'),
            'nursing_lang_id'=>$nursing_lang->id,
//            'cover_pepo_name'=>$data['cover_pepo_name'],
//            'cover_pepo_sex'=>$data['cover_pepo_sex'],
            'phone'=>$data['phone'],
            'contact_name'=>$data['contact_name'],
            'province'=>$data['province'],
            'city'=>$data['city'],
            'area'=>$data['area'],
            'address'=>$data['address'],
            'assessment_time'=>strtotime($data['assessment_time']),
            'uid'=>$user['id'],
            'is_assessment'=>1,
            'state'=>1,
            'status'=>1,
            'create_time'=>time(),
            'update_time'=>time(),
        ];
        $bool = NursingOrder::create($newdata);
        if(!$bool){
            return api_fail('预约失败');
        }
        $nursing_lang->inc('get_order_num_count',1)->update();
        return api_success('预约成功');
    }

    /**生成专业护理订单
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function nursing_order(Request $request){
        $user = $request->user;
        if(empty($user)){
            return api_fail('请先登录');
        }
        //控制用户使用频率
        $jiekou = cache('zhufu'.$user['id']);
        if($jiekou==1){
            return api_fail('请10秒后再次支付');
        }
        cache('zhufu'.$user['id'],1,10);
        $data = $request->param();
        $array = [
            'nursing_id|选择的服务'=>'require',
            'cover_pepo_name|被护理人的姓名'=>'require',
            'cover_pepo_sex|被护理人的性别'=>'require',
            'age|被护理人的年龄'=>'require',
            'is_live|是否住家'=>'require',
            'province|所在区域'=>'require',
            'city|所在区域'=>'require',
            'area|所在区域'=>'require',
            'address|详细地址'=>'require',
//            'address|详细地址'=>'require',
            'phone|联系电话'=>'require|mobile',
            'service_time|预约服务时间'=>'require',
        ];
        $this->validate($data,$array);
        $nursing_lang = NursingLang::where('status',1)
            ->where('id',$data['nursing_id'])
            ->find();
        if(empty($nursing_lang)){
            return api_fail('服务不存在');
        }
        $type = EscortType::where('id',$nursing_lang->getData('type_id'))
            ->find();
        if(empty($type)){
            return api_fail('没有查询到服务所属类型');
        }
//        echo '<pre>';
//        print_r($type->toArray());
//        exit;
        if($type->getData('types')==1){
            $days = $request->param('days');
            if(empty($days)){
                return api_fail('短期必须上传天数');
            }
        }elseif($type->getData('types')==2){
            $months = $request->param('months');
            if(empty($months)){
                return api_fail('长期必须上传月数');
            }
        }
        $obj = new AllOrder();
        $res = $obj->create_order($data,$user,$nursing_lang->toArray(),$type->toArray());
        if(!$res){
            return api_fail($obj->getMessage());
        }
        return api_success('获取成功',$res);
    }

    /**保姆下单
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function nanny_order(Request $request){
        $user = $request->user;
        if(empty($user)){
            return api_fail('请先登录');
        }
        //控制用户使用频率
//        $jiekou = cache('zhufu'.$user['id']);
//        if($jiekou==1){
//            return api_fail('请10秒后再次支付');
//        }
//        cache('zhufu'.$user['id'],1,10);
        $data = $request->param();
        $array = [
            'nursing_id|选择的服务'=>'require',
//            'cover_pepo_name|被护理人的姓名'=>'require',
//            'cover_pepo_sex|被护理人的性别'=>'require',
            'contact_name|联系人姓名'=>'require',
            'is_live|是否住家'=>'require',
            'province|所在区域'=>'require',
            'city|所在区域'=>'require',
            'area|所在区域'=>'require',
            'address|详细地址'=>'require',
//            'address|详细地址'=>'require',
            'phone|联系电话'=>'require|mobile',
            'house_area|房屋面积选项'=>'require',
            'three_meals|三餐制作'=>'require',
            'have_meals|用餐人数'=>'require',
            'meet_child|是否接送小孩'=>'require',
        ];
        $this->validate($data,$array);
        $nursing_lang = NursingLang::where('status',1)
            ->where('id',$data['nursing_id'])
            ->find();
        if(empty($nursing_lang)){
            return api_fail('服务不存在');
        }
        $type = EscortType::where('id',$nursing_lang->getData('type_id'))
            ->find();
        if(empty($type)){
            return api_fail('没有查询到服务所属类型');
        }
        if($type->getData('types')!=4){
            return  api_fail('请选择保姆的服务类型');
        }
        $obj = new AllOrder();
        $res = $obj->create_order($data,$user,$nursing_lang->toArray(),$type->toArray());
        if(!$res){
            return api_fail($obj->getMessage());
        }
        return api_success('获取成功',$res);
    }

    /**获取我的订单
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function get_order_list(Request $request){
        $state = $request->param('state',0);
        $limit = $request->param('limit',10);
        $user = $request->user;
        $where = [
            ['status','=',1],
            ['uid','=',$user['id']]
        ];
        if($state!=0){
            $where[] = ['state','=',$state];
        }
        $data = NursingOrder::where($where)
            ->field('id,assessment_time,service_time,nursing_lang_id,state')
            ->with(['nursing_lang'=>function($sql){
                $sql->field('id,name,img');
            }])
            ->order('create_time desc')
            ->paginate($limit)->toArray();
        return api_success('获取成功',$data['data']);
    }

    /**获取
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_order_info(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return api_fail('请输入要查询的服务');
        }
        $user = $request->user;
        $data = NursingOrder::where('id',$id)
            ->withoutField('sort,delete_time,status')
            ->with(['nursing_lang'=>function($sql){
                $sql->field('id,name,img');
            }])
            ->findOrEmpty()->toArray();
        if(empty($data)){
            return api_fail('订单不存在');
        }
        $comment = CommentUser::where('status',1)
            ->where('nursing_order_id',$id)
            ->where('uid',$user['id'])
            ->field('id,uid,nursing_order_id,staff_people_id,content,imgs,nursing_lang_id')
            ->with(['getuser'=>function($sql){
                $sql->field('id,name,head_img');
            }])
            ->findOrEmpty()->toArray();
//        echo '<pre>';
//        print_r($comment);
//        exit;
        $data['comment'] = $comment;
        return api_success('获取成功',$data);
    }

    /**获取平台费用
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_platform_money_list(Request $request){
        $type = $request->param('type',1);
        $platform = PlatformFee::where('type',$type)
            ->where('status',1)
            ->field('id,name,months,money,type')
            ->select()->toArray();
        if(empty($platform)){
            return api_fail('平台费用不存在');
        }
        return api_success('获取成功',$platform);
    }

    /**取消订单
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function order_cancel(Request $request){
        $user = $request->user;
        $id = $request->param('id');
        $quxiao = Cache::get('quxiao'.$user['id']);
        if($quxiao==1){
            return api_fail('请等上一个操作成功了在点击');
        }
        Cache::set('quxiao'.$user['id'],1,30);
        if(empty($id)){
            Cache::delete('quxiao'.$user['id']);
            return api_fail('请输入要取消的服务id');
        }
        $nursing_order = NursingOrder::where('status',1)
            ->where('id',$id)
            ->find();
        if(empty($nursing_order)){
            Cache::delete('quxiao'.$user['id']);
            return api_fail('订单不存在');
        }
        if(intval($user['id'])!==intval($nursing_order->uid)){
            Cache::delete('quxiao'.$user['id']);
            return api_fail('订单不属于你');
        }
        $message = '';
        if($nursing_order->getData('pay_state')==2){
            if(time()>=$nursing_order->getData('service_time')){
                Cache::delete('quxiao'.$user['id']);
                return api_fail('订单已经在服务中，请致电客服商议');
            }else{
                $obj = new AllOrder();
                $res = $obj->refundOrder($id,'取消服务');
                if($res===false){
                    Cache::delete('quxiao'.$user['id']);
                    return api_fail($obj->getMessage());
                }
                $message = '已申请退款，请耐心等待审核';
            }
        }
        $bool = NursingOrder::where('status',1)
            ->where('id',$id)
            ->save(['update_time'=>time(),'state'=>5]);
        if(!$bool){
            Cache::delete('quxiao'.$user['id']);
            return api_fail('取消订单失败');
        }
        Cache::delete('quxiao'.$user['id']);
        return api_success(empty($message)?'取消成功':$message);
    }

    /**获取服务续费信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function renew_order(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return api_fail('请输入要续费的订单');
        }
        $data = NursingOrder::where('id',$id)
            ->field('id,name,nursing_lang_id,cover_pepo_name,cover_pepo_sex,is_live,phone,province,city,area,address,service_time,age,end_time,contact_name,nanny_options_ids')
            ->findOrEmpty()->toArray();
        $data['nursing_id'] = $data['nursing_lang_id'];
        unset($data['nursing_lang_id']);
        $nursing_lang = NursingLang::where('id',$data['nursing_id'])
            ->findOrEmpty()->toArray();
        $type = EscortType::where('id',$nursing_lang['type_id'])
            ->findOrEmpty()->toArray();
        $data['types'] = $type['types'];
        if(strtotime($data['end_time'])<=time()){
            $data['service_time'] = date('Y-m-d H:i',(strtotime($data['end_time'])+86400));
        }else{
            $data['service_time'] = '';
        }
        unset($data['end_time']);
        return api_success('获取成功',$data);
    }

    /**添加意见反馈
     * @param Request $request
     * @return \think\response\Json
     */
    public function add_feedback(Request $request){
        $user = $request->user;
        $fankui = Cache::get('fenkui'.$user['id']);
        if($fankui==1){
            return api_fail('请稍等10秒后提交');
        }
        Cache::set('fenkui'.$user['id'],1,10);
        $data = $request->param();
        $array = [
            'phone|用户联系电话'=>'require|mobile',
            'opinions|意见和反馈内容'=>'require',
        ];
        $this->validate($data,$array);
        $newdata = [
            'uid'=>$user['id'],
            'phone'=>$data['phone'],
            'opinions'=>$data['opinions'],
            'state'=>0,
            'status'=>1,
            'create_time'=>time(),
            'update_time'=>time(),
        ];
        $bool = Feedback::create($newdata);
        if(!$bool){
            return api_fail('提交失败,请稍后');
        }
        return api_success('提交成功');
    }

    /**评价服务
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add_evaluate(Request $request){
        $data = $request->param();
        $user = $request->user;
        $array = [
            'id|要评论得订单'=>'require',
            'evaluate|评价'=>'require',
            'content|评论内容'=>'require',
        ];
        $this->validate($data,$array);
        $order = NursingOrder::find($data['id']);
        if(empty($order)){
            return api_fail('订单不存在');
        }
        if(intval($order->getData('uid'))!==intval($user['id'])){
            return api_fail('订单不属于你');
        }
        $newdata = [
            'name'=>$order->name,
            'uid'=>$order->getData('uid'),
            'nursing_order_id'=>$order->getData('id'),
            'staff_people_id'=>$order->getData('staff_people_id'),
            'content'=>$data['content'],
            'nursing_lang_id'=>$order->getData('nursing_lang_id'),
            'evaluate'=>$data['evaluate'],
            'status'=>1,
            'create_time'=>time(),
            'update_time'=>time(),
        ];
        if(isset($data['imgs'])&&$data['imgs']){
            if(is_array($data['imgs'])){
                $data['imgs'] = implode('|',$data['imgs']);
            }
            $newdata['imgs'] = $data['imgs'];
        }
        $bool = CommentUser::create($newdata);
        $order->state = 4;
        if(!$bool){
            return api_fail('评论失败');
        }
        $order->save(['update_time'=>time()]);
        return api_success('评论成功');
    }

    /**获取订单签到数据
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_check_info(Request $request){
        $id = $request->param('id');
//        $user = $request->user;
        if(empty($id)){
            return api_fail('请输入要查询的订单');
        }
        $date = $request->param('date');
        if(empty($date)){
            list($start,$end) = HerTime::today();
        }else{
            list($start,$end) = HerTime::today(strtotime($date));
        }
        $data = OrderCheck::where('status',1)
            ->where('nursing_order_id',$id)
            ->where('create_time','>',$start)
            ->where('create_time','<=',$end)
            ->withoutField('status,delete_time,nursing_order_id,update_time')
            ->findOrEmpty()->toArray();
        if(empty($data)){
            return api_fail('没有签到信息');
        }
        $data['create_time'] = date('Y-m-d H:i',strtotime($data['create_time']));
        return api_success('获取成功',$data);
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_option(Request $request){
        $type = $request->param('type');
        if(empty($type)){
            return api_fail('请输入类型');
        }
        $where[] = ['nursing_lang_id','=',13];
        $where[] = ['name','=',$type];
        $data = OptionType::where($where)
            ->field('id,name')
            ->findOrEmpty()->toArray();
        if(empty($data)){
            return api_fail('未获取分类');
        }
        $child = NannyOptions::where('status',1)
            ->where('option_type_id',$data['id'])
            ->order('sort desc')
            ->field('id,name,money')
            ->select()->toArray();
        return api_success('获取成功',$child);
    }
}